package org.elanfox.cloud.common.web.config;

import cn.hutool.core.util.ArrayUtil;
import org.elanfox.cloud.common.web.base.JwtProvider;
import org.elanfox.cloud.common.web.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author allan
 * @version 1.0.0
 * @date 2/24/21
 */
@Configuration
@EnableConfigurationProperties({SecurityProperties.class, JwtProvider.class})
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private SecurityProperties securityProperties;

    private static final String[] STATIC_RESOURCE_PATH = {
            "classpath:/resource/**",
            "/resource/**",
            "/swagger-ui.html",
            "/swagger-resources/**",
            "/webjars/springfox-swagger-ui/**",
            "/swagger/**",
            "/**/v2/api-docs",
            "/actuator/**",
            "/test/**"
    };

    @Override
    public void configure(WebSecurity web) {
        String[] ignoreUris = ArrayUtil.addAll(STATIC_RESOURCE_PATH, securityProperties.getIgnoreUris());
        web.ignoring().antMatchers(ignoreUris);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers().frameOptions().sameOrigin()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                .antMatchers(STATIC_RESOURCE_PATH)
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .cors()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(null, UsernamePasswordAuthenticationFilter.class);
    }
}
